package xyz.csmcool.imutil.ExceptionHandler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.csmcool.imutil.utils.ResultTool;
import xyz.csmcool.imutil.webVo.ResultCode;
import xyz.csmcool.imutil.webVo.ResultVo;

/**
 * @author 什锦
 * @Package xyz.csmcool.imutil.webVo
 * @since 2022/7/31 14:22
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVo handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return ResultTool.fail(ResultCode.CUSTOM_FAIL.setCode(999).setMessage(e.getBindingResult().getFieldError().getDefaultMessage()));
    }

    /**
     * @param e
     * @return JsonResult
     * 指定出现什么异常执行这个方法
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultVo error(Exception e){
        e.printStackTrace();
        return ResultTool.fail(ResultCode.COMMON_FAIL.setMessage(e.getMessage()));
    }


    @ExceptionHandler(CommunityException.class)
    @ResponseBody
    public ResultVo error(CommunityException e){
        return ResultTool.fail(ResultCode.CUSTOM_FAIL.setCode(e.getCode()).setMessage(e.getMsg()));
    }

    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public ResultVo error(CommonException e){
        return ResultTool.fail(e.getResultCode());
    }

}
